package com.cskaoyan.user.controller;




import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.user.form.KaptchaCodeRequest;
import com.cskaoyan.user.dto.KaptchaCodeResponse;
import com.cskaoyan.user.service.IKaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

@RestController
@RequestMapping("/user")
public class CaptchaController {

    @Autowired
    IKaptchaService kaptchaService;

    /**
     * 获取验证码
     */
    @GetMapping("/kaptcha")
    public ResponseData getKaptchaCode(HttpServletResponse response) {
        KaptchaCodeResponse kaptchaCodeResponse = kaptchaService.getKaptchaCode();
        Cookie cookie = CookieUtil.genCookie("kaptcha_uuid", kaptchaCodeResponse.getUuid(), "/", 60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return new ResponseUtil<>().setData(kaptchaCodeResponse.getImageCode());

    }

    @PostMapping("/kaptcha")
    public ResponseData validKaptchaCode(@NotNull @RequestBody String code, HttpServletRequest httpServletRequest) {
        KaptchaCodeRequest request = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(httpServletRequest, "kaptcha_uuid");
        request.setUuid(uuid);
        request.setCode(code);
        kaptchaService.validateKaptchaCode(request);
        return new ResponseUtil<>().setData(null);


    }
}
